package io.shuttle.mbe.api

import io.shuttle.mbe.api.annotation.ChromeMinVersion
import io.shuttle.mbe.api.annotation.ForegroudOnly
import io.shuttle.mbe.api.annotation.PromiseStyleMinVersion
import io.shuttle.mbe.api.types.DirectoryEntry
import io.shuttle.mbe.api.types.StringOrStringArr
import io.shuttle.mbe.api.types.Value1Function
import io.shuttle.mbe.api.types.Value2Function
import io.shuttle.mbe.api.types.Value3Function
import io.shuttle.mbe.api.types.Value3ReturnFunction
import io.shuttle.mbe.api.types.VoidFunction
import io.shuttle.mbe.api.types.Window
import io.shuttle.mbe.core.Promise
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

////////////////////
// Runtime
////////////////////
/**
 * Use the `Browser.runtime` API to retrieve the service worker, return details about the manifest, and listen for and respond to events in the extension lifecycle. You can also use this API to convert the relative path of URLs to fully-qualified URLs.
 */
interface Runtime {
    // The ID of the extension/app.
    val id: String

    // Populated with an error message if calling an API function fails; otherwise undefined. This is only defined within the scope of that function's callback. If an error is produced, but runtime.lastError is not accessed within the callback, a message is logged to the console listing the API function that produced the error. API functions that return promises do not set this property.
    val lastError: LastError?

    // Details about the error which occurred.
    val message: String?

    // Attempts to connect listeners within an extension (such as the background page), or other extensions/apps. This is useful for content scripts connecting to their extension processes, inter-app/extension communication, and web messaging. Note that this does not connect to any listeners in a content script. Extensions may connect to content scripts embedded in tabs via tabs.connect.
    // @return Port through which messages can be sent and received. The port's onDisconnect event is fired if the extension does not exist.
    fun connect(
        // The ID of the extension to connect to. If omitted, a connection will be attempted with your own extension. Required if sending messages from a web page for web messaging.
        extensionId: String?,
        connectInfo: ConnectionInfo?
    ): Port

    // Connects to a native application in the host machine. This method requires the "nativeMessaging" permission. See Native Messaging for more information.
    // @return Port through which messages can be sent and received with the application
    fun connectNative(
        // The name of the registered application to connect to.
        application: String
    ): Port

    // Retrieves the JavaScript 'window' object for the background page running inside the current extension/app. If the background page is an event page, the system will ensure it is loaded before calling the callback. If there is no background page, an error is set.
    // @return {callback.backgroundPage} The JavaScript 'window' object for the background page.
    @ForegroudOnly
    @Deprecated(
        "Deprecated since Chrome 133",
        replaceWith = ReplaceWith("Background pages do not exist in MV3 extensions.")
    )
    @PromiseStyleMinVersion(99)
    fun getBackgroundPage(
        callback: Value1Function<Window?>? = null
    ): Promise<Window?>

    /**
     * Fetches information about active contexts associated with this extension
     * @param filter A filter to find matching contexts. A context matches if it matches all specified fields in the filter. Any unspecified field in the filter matches all contexts.
     * @since Chrome 116 MV3.
     */
    @ChromeMinVersion(116)
    @PromiseStyleMinVersion(99)
    fun getContexts(
        filter: ContextFilter,
        callback: Value1Function<List<ExtensionContext>>? = null
    ): Promise<List<ExtensionContext>>

    // Returns details about the app or extension from the manifest. The object returned is a serialization of the full manifest file.
    fun getManifest(): Manifest

    // Returns a DirectoryEntry for the package directory.
    @ForegroudOnly
    @PromiseStyleMinVersion(122)
    fun getPackageDirectoryEntry(callback: Value1Function<DirectoryEntry>? = null): Promise<DirectoryEntry>

    // Returns information about the current platform.
    @PromiseStyleMinVersion(99)
    fun getPlatformInfo(callback: Value1Function<PlatformInfo>? = null): Promise<PlatformInfo>

    // Converts a relative path within an app/extension install directory to a fully-qualified URL.
    // @param {String} A path to a resource within an app/extension expressed relative to its install directory.
    // @return {String} The fully-qualified URL to the resource.
    fun getURL(path: String): String

    // Open your Extension's options page, if possible.
    //
    //The precise behavior may depend on your manifest's options_ui or options_page key, or what Chrome happens to support at the time. For example, the page may be opened in a new tab, within chrome://extensions, within an App, or it may just focus an open options page. It will never cause the caller page to reload.
    //
    //If your Extension does not declare an options page, or Chrome failed to create one for some other reason, the callback will set lastError.
    @PromiseStyleMinVersion(99)
    fun openOptionsPage(callback: VoidFunction? = null): Promise<Void>

    // Reloads the app or extension. This method is not supported in kiosk mode. For kiosk mode, use chrome.runtime.restart() method.
    fun reload()

    // Requests an immediate update check be done for this app/extension.
    //
    //Important: Most extensions/apps should not use this method, since Chrome already does automatic checks every few hours, and you can listen for the runtime.onUpdateAvailable event without needing to call requestUpdateCheck.
    //
    //This method is only appropriate to call in very limited circumstances, such as if your extension talks to a backend service, and the backend service has determined that the client extension version is very far out of date and you'd like to prompt a user to update. Most other uses of requestUpdateCheck, such as calling it unconditionally based on a repeating timer, probably only serve to waste client, network, and server resources.
    //
    //Note: When called with a callback, instead of returning an object this function will return the two properties as separate arguments passed to the callback.
    @PromiseStyleMinVersion(109)
    fun requestUpdateCheck(callback: Value1Function<RequestUpdateCheckResult>? = null): Promise<RequestUpdateCheckResult>

    // Restart the ChromeOS device when the app runs in kiosk mode. Otherwise, it's no-op.
    fun restart()

    // Restart the ChromeOS device when the app runs in kiosk mode after the given seconds. If called again before the time ends, the reboot will be delayed. If called with a value of -1, the reboot will be cancelled. It's a no-op in non-kiosk mode. It's only allowed to be called repeatedly by the first extension to invoke this API.
    // @params {Number} Time to wait in seconds before rebooting the device, or -1 to cancel a scheduled reboot.
    @PromiseStyleMinVersion(99)
    @ChromeMinVersion(53)
    fun restartAfterDelay(seconds: Number, callback: VoidFunction? = null): Promise<Void>

    // Sends a single message to event listeners within your extension or a different extension/app. Similar to runtime.connect but only sends a single message, with an optional response. If sending to your extension, the runtime.onMessage event will be fired in every frame of your extension (except for the sender's frame), or runtime.onMessageExternal, if a different extension. Note that extensions cannot send messages to content scripts using this method. To send messages to content scripts, use tabs.sendMessage.
    // @return {callback.response} The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message.
    @PromiseStyleMinVersion(99)
    fun sendMessage(
        // The ID of the extension to send the message to. If omitted, the message will be sent to your own extension/app. Required if sending messages from a web page for web messaging.
        extensionId: String?,
        // The message to send. This message should be a JSON-ifiable object.
        message: Any,
        options: SendMessageOptions?,
        callback: Value1Function<Any>? = null
    ): Promise<Any>

    // Send a single message to a native application. This method requires the "nativeMessaging" permission.
    // @return {callback.response} The JSON response object sent by the handler of the message. If an error occurs while connecting to the extension, the callback will be called with no arguments and runtime.lastError will be set to the error message.
    @PromiseStyleMinVersion(99)
    fun sendNativeMessage(
        // The name of the native messaging host.
        application: String,
        // The message that will be passed to the native messaging host.
        message: Any,
        callback: Value1Function<Any>? = null
    ): Promise<Any>

    // Sets the URL to be visited upon uninstallation. This may be used to clean up server-side data, do analytics, and implement surveys. Maximum 1023 characters.
    @PromiseStyleMinVersion(99)
    fun setUninstallURL(
        // URL to be opened after the extension is uninstalled. This URL must have an http: or https: scheme. Set an empty string to not open a new tab upon uninstallation.
        url: String,
        @ChromeMinVersion(45)
        callback: VoidFunction? = null
    ): Promise<Void>

    // Fired when a Chrome update is available, but isn't installed immediately because a browser restart is required.
    @Deprecated("Deprecated", replaceWith = ReplaceWith("Please use runtime.onRestartRequired."))
    val onBrowserUpdateAvailable: Events.Event<VoidFunction>

    // Fired when a connection is made from either an extension process or a content script (by runtime.connect).
    val onConnect: Events.Event<Value1Function<Port>>

    // Fired when a connection is made from another extension (by runtime.connect), or from an externally connectable web site.
    val onConnectExternal: Events.Event<Value1Function<Port>>

    // Fired when a connection is made from a native application. This event requires the "nativeMessaging" permission. It is only supported on Chrome OS.
    @ChromeMinVersion(76)
    val onConnectNative: Events.Event<Value1Function<Port>>

    // Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version.
    val onInstalled: Events.Event<Value1Function<OnInstallDetails>>

    // Fired when a message is sent from either an extension process (by runtime.sendMessage) or a content script (by tabs.sendMessage).
    // @callback (message: any, sender: MessageSender, sendResponse: function) => boolean | undefined
    val onMessage: Events.Event<Value3ReturnFunction<Any, MessageSender, VoidFunction, Boolean?>>

    // Fired when a message is sent from another extension (by runtime.sendMessage). Cannot be used in a content script.
    // @callback (message: any, sender: MessageSender, sendResponse: function) => boolean | undefined
    val onMessageExternal: Events.Event<Value3ReturnFunction<Any, MessageSender, VoidFunction, Boolean?>>

    // Fired when an app or the device that it runs on needs to be restarted. The app should close all its windows at its earliest convenient time to let the restart to happen. If the app does nothing, a restart will be enforced after a 24-hour grace period has passed. Currently, this event is only fired for Chrome OS kiosk apps.
    val onRestartRequired: Events.Event<Value1Function<OnRestartRequiredReason>>

    // Fired when a profile that has this extension installed first starts up. This event is not fired when an incognito profile is started, even if this extension is operating in 'split' incognito mode.
    val onStartup: Events.Event<VoidFunction>

    // Sent to the event page just before it is unloaded. This gives the extension opportunity to do some clean up. Note that since the page is unloading, any asynchronous operations started while handling this event are not guaranteed to complete. If more activity for the event page occurs before it gets unloaded the onSuspendCanceled event will be sent and the page won't be unloaded.
    val onSuspend: Events.Event<VoidFunction>

    // Sent after onSuspend to indicate that the app won't be unloaded after all.
    val onSuspendCanceled: Events.Event<VoidFunction>

    // Fired when an update is available, but isn't installed immediately because the app is currently running. If you do nothing, the update will be installed the next time the background page gets unloaded, if you want it to be installed sooner you can explicitly call chrome.runtime.reload(). If your extension is using a persistent background page, the background page of course never gets unloaded, so unless you call chrome.runtime.reload() manually in response to this event the update will not get installed until the next time Chrome itself restarts. If no handlers are listening for this event, and your extension has a persistent background page, it behaves as if chrome.runtime.reload() is called in response to this event.
    val onUpdateAvailable: Events.Event<Value1Function<OnUpdateAvailableDetails>>

    /**
     * Fired when a connection is made from a user script from this extension.
     * @since chrome 115 MV3
     */
    @ChromeMinVersion(115)
    val onUserScriptContent: Events.Event<Value1Function<Port>>

    /**
     * Fired when a message is sent from a user script associated with the same extension.
     * @since chrome 115, MV3
     * @param message
     * @param sender
     * @param sendResponse
     */
    @ChromeMinVersion(115)
    val onUserScriptMessage: Events.Event<Value3Function<Any, MessageSender, Value1Function<Any>>>

    // A filter to match against certain extension contexts. Matching contexts must match all specified filters; any filter that is not specified matches all available contexts. Thus, a filter of `{}` will match all available contexts.
    @ChromeMinVersion(114)
    data class ContextFilter(
        var contextIds: List<String>?,
        var contextTypes: List<ContextType>?,
        var documentIds: List<String>?,
        var documentOrigins: List<String>?,
        var documentUrls: List<String>?,
        var frameIds: List<Number>?,
        var incognito: Boolean?,
        var tabIds: List<String>?,
        var windowIds: List<Number>?
    )

    /** Details about the error which occurred.  */
    data class LastError(var message: String?)

    @ChromeMinVersion(114)
    enum class ContextType {
        // Specifies the context type as a tab
        TAB,

        // Specifies the context type as an extension popup window
        POPUP,

        // Specifies the context type as a service worker.
        BACKGROUND,

        // Specifies the context type as an offscreen document.
        OFFSCREEN_DOCUMENT,

        // Specifies the context type as a side panel.
        SIDE_PANEL,

        // Specifies the context type as developer tools.
        DEVELOPER_TOOLS
    }

    // A context hosting extension content.
    @ChromeMinVersion(114)
    data class ExtensionContext(
        // A unique identifier for this context
        var contextId: String,
        // The type of context this corresponds to.
        var contextType: ContextType,
        // A UUID for the document associated with this context, or undefined if this context is hosted not in a document.
        var documentId: String?,
        // The origin of the document associated with this context, or undefined if the context is not hosted in a document.
        var documentOrigin: String?,
        // The URL of the document associated with this context, or undefined if the context is not hosted in a document.
        var documentUrl: String?,
        // The ID of the frame for this context, or -1 if this context is not hosted in a frame.
        var frameId: Number,
        // Whether the context is associated with an incognito profile.
        var incognito: Boolean,
        // The ID of the tab for this context, or -1 if this context is not hosted in a tab.
        var tabId: Number,
        // The ID of the window for this context, or -1 if this context is not hosted in a window.
        var windowId: Number
    )

    // An object containing information about the script context that sent a message or request.
    data class MessageSender(
        // A UUID of the document that opened the connection.
        @ChromeMinVersion(106)
        var documentId: String?,
        // The lifecycle the document that opened the connection is in at the time the port was created. Note that the lifecycle state of the document may have changed since port creation.
        @ChromeMinVersion(106)
        var documentLifecycle: String?,
        // The frame that opened the connection. 0 for top-level frames, positive for child frames. This will only be set when tab is set.
        var frameId: Number?,
        // The ID of the extension that opened the connection, if any.
        var id: String?,
        // The name of the native application that opened the connection, if any.
        @ChromeMinVersion(74)
        var nativeApplication: String?,
        // The origin of the page or frame that opened the connection. It can vary from the url property (e.g., about:blank) or can be opaque (e.g., sandboxed iframes). This is useful for identifying if the origin can be trusted if we can't immediately tell from the URL.
        @ChromeMinVersion(80)
        var origin: String?,
        // The tabs.Tab which opened the connection, if any. This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app.
        var tab: Tabs.Tab?,
        // The TLS channel ID of the page or frame that opened the connection, if requested by the extension, and if available.
        var tlsChannelId: String?,
        // The URL of the page or frame that opened the connection. If the sender is in an iframe, it will be iframe's URL not the URL of the page which hosts it.
        var url: String?,
    )

    // The reason that this event is being dispatched.
    @ChromeMinVersion(44)
    enum class OnInstalledReason {
        // Specifies the event reason as an installation.
        install,

        // Specifies the event reason as an extension update.
        update,

        // Specifies the event reason as a Chrome update.
        chrome_update,

        // Specifies the event reason as an update to a shared module.
        shared_module_update
    }

    // The reason that the event is being dispatched. 'app_update' is used when the restart is needed because the application is updated to a newer version. 'os_update' is used when the restart is needed because the browser/OS is updated to a newer version. 'periodic' is used when the system runs for more than the permitted uptime set in the enterprise policy.
    @ChromeMinVersion(44)
    enum class OnRestartRequiredReason {
        // Specifies the event reason as an update to the app.
        app_update,

        // Specifies the event reason as an update to the operating system.
        os_update,

        // Specifies the event reason as a periodic restart of the app.
        periodic
    }

    enum class PlatformArch {
        arm,
        arm64,
        x86_32,
        x86_64,
        mips,
        mips64,
        riscv64
    }

    // An object containing information about the current platform.
    data class PlatformInfo(
        // The machine's processor architecture.
        var arch: PlatformArch,
        // The native client architecture. This may be different from arch on some platforms.
        var nacl_arch: PlatformNaclArch?,
        // The operating system Chrome is running on.
        var os: PlatformOs,
    )

    // The native client architecture. This may be different from arch on some platforms.
    @ChromeMinVersion(44)
    enum class PlatformNaclArch {
        arm,
        x86_32,
        x86_64,
        mips,
        mips64,
    }

    // The operating system Chrome is running on.
    @ChromeMinVersion(44)
    enum class PlatformOs {
        mac,
        win,
        android,
        cros,
        linux,
        openbsd,
        fuchsia
    }

    // An object which allows two way communication with other pages. See Long-lived connections for more information.
    data class Port(
        // The name of the port, as specified in the call to runtime.connect.
        var name: String,
        // Fired when the port is disconnected from the other end(s). runtime.lastError may be set if the port was disconnected by an error. If the port is closed via disconnect, then this event is only fired on the other end. This event is fired at most once (see also Port lifetime).
        var onDisconnect: Value1Function<Port>? = null,
        // This event is fired when postMessage is called by the other end of the port.
        var onMessage: Value2Function<Any, Port>? = null,
        // This property will only be present on ports passed to onConnect / onConnectExternal / onConnectNative listeners.
        var sender: MessageSender?,
        // Immediately disconnect the port. Calling disconnect() on an already-disconnected port has no effect. When a port is disconnected, no new events will be dispatched to this port.
        var disconnect: VoidFunction? = null,
        // Send a message to the other end of the port. If the port is disconnected, an error is thrown.
        // @callback The message to send. This object should be JSON-ifiable.
        @ChromeMinVersion(52)
        var postMessage: Value1Function<Any>? = null,
    )

    // Result of the update check.
    @ChromeMinVersion(44)
    enum class RequestUpdateCheckStatus {
        // Specifies that the status check has been throttled. This can occur after repeated checks within a short amount of time.
        throttled,

        // Specifies that there are no available updates to install.
        no_update,

        // Specifies that there is an available update to install.
        update_available
    }

    data class ConnectionInfo(
        // Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event.
        var includeTlsChannelId: Boolean?,
        // Will be passed into onConnect for processes that are listening for the connection event.
        var name: String?,
    )

    data class SendMessageOptions(
        // Whether the TLS channel ID will be passed into onConnectExternal for processes that are listening for the connection event.
        var includeTlsChannelId: Boolean?,
    )

    // RequestUpdateCheckResult object that holds the status of the update check and any details of the result if there is an update available
    data class RequestUpdateCheckResult(
        // Result of the update check.
        var status: RequestUpdateCheckStatus,
        // If an update is available, this contains the version of the available update.
        var version: String?,
    )

    data class OnInstallDetails(
        // Indicates the ID of the imported shared module extension which updated. This is present only if 'reason' is 'shared_module_update'.
        var id: String?,
        // Indicates the previous version of the extension, which has just been updated. This is present only if 'reason' is 'update'.
        var previousVersion: String?,
        // The reason that this event is being dispatched.
        var reason: OnInstalledReason,
    )

    data class OnUpdateAvailableDetails(
        // The version number of the available update.
        var version: String,
    )

    data class ManifestAction(
        var default_icon: ManifestIcons?,
        var default_title: String?,
        var default_popup: String?
    )

    /** Source: https://developer.chrome.com/docs/extensions/reference/permissions-list */
    @Serializable
    enum class ManifestPermissions {
        @SerialName("accessibilityFeatures.modify")
        accessibilityFeatures_modify,

        @SerialName("accessibilityFeatures.read")
        accessibilityFeatures_read,
        activeTab,
        alarms,
        audio,
        background,
        bookmarks,
        browsingData,
        certificateProvider,
        clipboardRead,
        clipboardWrite,
        contentSettings,
        contextMenus,
        cookies,
        debugger,
        declarativeContent,
        declarativeNetRequest,
        declarativeNetRequestFeedback,
        declarativeNetRequestWithHostAccess,
        declarativeWebRequest,
        desktopCapture,
        documentScan,
        downloads,

        @SerialName("downloads.open")
        downloads_open,

        @SerialName("downloads.shelf")
        downloads_shelf,

        @SerialName("downloads.ui")
        downloads_ui,

        @SerialName("enterprise.deviceAttributes")
        enterprise_deviceAttributes,

        @SerialName("enterprise.hardwarePlatform")
        enterprise_hardwarePlatform,

        @SerialName("enterprise.login")
        enterprise_login,

        @SerialName("enterprise.networkingAttributes")
        enterprise_networkingAttributes,

        @SerialName("enterprise.platformKeys")
        enterprise_platformKeys,
        experimental,
        favicon,
        fileBrowserHandler,
        fileSystemProvider,
        fontSettings,
        gcm,
        geolocation,
        history,
        identity,

        @SerialName("identity.email")
        identity_email,
        idle,
        loginState,
        management,
        nativeMessaging,
        notifications,
        offscreen,
        pageCapture,
        platformKeys,
        power,
        printerProvider,
        printing,
        printingMetrics,
        privacy,
        processes,
        proxy,
        readingList,
        scripting,
        search,
        sessions,
        sidePanel,
        storage,

        @SerialName("system.cpu")
        system_cpu,

        @SerialName("system.display")
        system_display,

        @SerialName("system.memory")
        system_memory,

        @SerialName("system.storage")
        system_storage,
        systemLog,
        tabCapture,
        tabGroups,
        tabs,
        topSites,
        tts,
        ttsEngine,
        unlimitedStorage,
        userScripts,
        vpnProvider,
        wallpaper,
        webAuthenticationProxy,
        webNavigation,
        webRequest,
        webRequestBlocking,
        webRequestAuthProvider
    }

    /** Source : https://developer.chrome.com/docs/extensions/reference/api/permissions */
    enum class ManifestOptionalPermissions {
        @SerialName("accessibilityFeatures.modify")
        accessibilityFeatures_modify,

        @SerialName("accessibilityFeatures.read")
        accessibilityFeatures_read,
        activeTab,
        alarms,
        audio,
        background,
        bookmarks,
        browsingData,
        certificateProvider,
        clipboardRead,
        clipboardWrite,
        contentSettings,
        contextMenus,
        cookies,
        declarativeContent,
        declarativeNetRequestFeedback,
        declarativeNetRequestWithHostAccess,
        declarativeWebRequest,
        desktopCapture,
        documentScan,
        downloads,

        @SerialName("downloads.open")
        downloads_open,

        @SerialName("downloads.shelf")
        downloads_shelf,

        @SerialName("downloads.ui")
        downloads_ui,

        @SerialName("enterprise.deviceAttributes")
        enterprise_deviceAttributes,

        @SerialName("enterprise.hardwarePlatform")
        enterprise_hardwarePlatform,

        @SerialName("enterprise.login")
        enterprise_login,

        @SerialName("enterprise.networkingAttributes")
        enterprise_networkingAttributes,

        @SerialName("enterprise.platformKeys")
        enterprise_platformKeys,
        favicon,
        fileBrowserHandler,
        fileSystemProvider,
        gcm,
        history,
        identity,

        @SerialName("identity.email")
        identity_email,
        idle,
        loginState,
        management,
        nativeMessaging,
        notifications,
        offscreen,
        pageCapture,
        platformKeys,
        power,
        printerProvider,
        printing,
        printingMetrics,
        privacy,
        processes,
        readingList,
        scripting,
        search,
        sessions,
        sidePanel,
        storage,

        @SerialName("system.cpu")
        system_cpu,

        @SerialName("system.display")
        system_display,

        @SerialName("system.memory")
        system_memory,

        @SerialName("system.storage")
        system_storage,
        systemLog,
        tabCapture,
        tabGroups,
        tabs,
        topSites,
        userScripts,
        vpnProvider,
        webNavigation,
        webRequest,
        webRequestBlocking,
        webRequestAuthProvider
    }

    data class SearchProvider(
        var name: String?,
        var keyword: String?,
        var favicon_url: String?,
        var search_url: String,
        var encoding: String?,
        var suggest_url: String?,
        var instant_url: String?,
        var image_url: String?,
        var search_url_post_params: String?,
        var suggest_url_post_params: String?,
        var instant_url_post_params: String?,
        var image_url_post_params: String?,
        var alternate_urls: List<String>?,
        var prepopulated_id: Int?,
        var is_default: Boolean?
    )

    data class Author(var email: String)
    data class ChromeSettingsOverrides(
        var homepage: String?,
        var search_provider: SearchProvider?,
        var startup_pages: List<String>?
    )

    data class ChromeUiOverrides(
        var bookmarks_ui: BookmarksUi?
    )

    data class BookmarksUi(
        var remove_bookmark_shortcut: Boolean?,
        var remove_button: Boolean?
    )

    data class ChromeUrlOverrides(
        var bookmarks: String?,
        var history: String?,
        var newtab: String?
    )

    data class CommandItem(
        var global: Boolean?,
        var description: String?,
        var suggested_key: CommandItemSuggestedKey?
    )

    data class CommandItemSuggestedKey(
        var default: String?,
        var window: String?,
        var mac: String?,
        var chromeos: String?,
        var linux: String?
    )

    data class ContentCapabilities(
        var matches: List<String>?,
        var permissions: List<String>?
    )

    open class ContentScript(
        open var matches: List<String>?,
        open var exclude_matches: List<String>?,
        open var css: List<String>?,
        open var js: List<String>?,
        open var run_at: String?,
        open var all_frames: Boolean?,
        open var match_about_blank: Boolean?,
        open var include_globs: List<String>?,
        open var exclude_globs: List<String>?
    )

    data class ContentScriptV3(
        override var matches: List<String>?,
        override var exclude_matches: List<String>?,
        override var css: List<String>?,
        override var js: List<String>?,
        override var run_at: String?,
        override var all_frames: Boolean?,
        override var match_about_blank: Boolean?,
        override var include_globs: List<String>?,
        override var exclude_globs: List<String>?,
        var world: ContentScriptV3World?
    ) : ContentScript(
        matches,
        exclude_globs,
        css,
        js,
        run_at,
        all_frames,
        match_about_blank,
        include_globs,
        exclude_globs
    )

    enum class ContentScriptV3World {
        ISOLATED,
        MAIN
    }

    data class EventRule(
        var event: String?,
        var conditions: List<DeclarativeContent.PageStateMatcher>?,
        var actions: List<EventRuleAction>?,
    )

    data class EventRuleAction(var type: String)

    data class ExternallyConnectable(
        var ids: List<String>?,
        var matches: List<String>?,
        var accepts_tls_channel_id: Boolean?
    )

    data class FileBrowserHandler(
        var id: String?,
        var default_title: String?,
        var file_filters: List<String>?
    )

    data class FileSystemProviderCapabilities(
        var configurable: Boolean?,
        var watchable: Boolean?,
        var multiple_mounts: Boolean?,
        var source: String?
    )

    data class Import(var id: String, var minimum_version: String?)
    data class Export(var whitelist: List<String>?)

    data class InputComponent(
        var name: String?,
        var type: String?,
        var id: String?,
        var description: String?,
        var language: StringOrStringArr?,
        var layouts: List<String>?,
        var indicator: String?
    )

    data class NaclModule(var path: String, var mime_type: String)
    data class OAuth2(var client_id: String, var scopes: List<String>?)
    data class Omnibox(var keyword: String)
    data class OptionsUi(
        var page: String?,
        var chrome_style: Boolean?,
        var open_in_tab: Boolean?
    )

    data class Platform(var nacl_arch: String?, var sub_package_path: String)
    data class Plugin(var path: String)
    data class Requirements(var `3D`: Requirements3D?, var plugins: RequirementsPlugins?)
    data class Requirements3D(var features: List<String>?)
    data class RequirementsPlugins(var npapi: Boolean?)
    data class Sandbox(var pages: List<String>?, var content_security_policy: String?)
    data class Spellcheck(
        var dictionary_language: String?,
        var dictionary_locale: String?,
        var dictionary_format: String?,
        var dictionary_path: String?
    )

    data class Storage(var managed_schema: String)
    data class TtsEngine(var voices: List<TtsEngineVoice>?)
    data class TtsEngineVoice(
        var voice_name: String,
        var lang: String?,
        var gender: String?,
        var event_types: List<String>?
    )

    abstract class ManifestBase(
        // Required
        open var manifest_version: Number,
        open var name: String,
        open var version: String,
        // Recommended
        open var default_locale: String? = null,
        open var description: String? = null,
        open var icons: ManifestIcons? = null,
        // Optional
        open var author: Author? = null,
        open var background_page: String? = null,
        open var chrome_settings_overrides: ChromeSettingsOverrides? = null,
        open var chrome_ui_overrides: ChromeUiOverrides? = null,
        open var chrome_url_overrides: ChromeUrlOverrides? = null,
        open var commands: Map<String, CommandItem>? = null,
        open var content_capabilities: ContentCapabilities? = null,
        open var content_scripts: List<ContentScript>? = null,
        open var converted_from_user_script: Boolean? = null,
        open var current_locale: String? = null,
        open var devtools_page: String? = null,
        open var event_rules: List<EventRule>? = null,
        open var externally_connectable: ExternallyConnectable? = null,
        open var file_browser_handlers: List<FileBrowserHandler>? = null,
        open var file_system_provider_capabilities: FileSystemProviderCapabilities? = null,
        open var homepage_url: String? = null,
        open var import: List<Import>? = null,
        open var export: Export? = null,
        open var incognito: String? = null,
        open var input_components: List<InputComponent>? = null,
        open var key: String? = null,
        open var minimum_chrome_version: String? = null,
        open var nacl_modules: List<NaclModule>? = null,
        open var oauth2: OAuth2? = null,
        open var offline_enabled: Boolean? = null,
        open var omnibox: Omnibox? = null,
        open var options_page: String? = null,
        open var options_ui: OptionsUi? = null,
        open var platforms: List<Platform>? = null,
        open var plugins: List<Plugin>? = null,
        open var requirements: Requirements? = null,
        open var sandbox: Sandbox? = null,
        open var spellcheck: Spellcheck? = null,
        open var storage: Storage? = null,
        open var tts_engine: TtsEngine? = null,
        open var update_url: String? = null,
        open var version_name: String? = null,
        open var customFiled: Map<String, Any>? = null
    )

    data class Background(
        var scripts: List<String>?,
        var page: String?,
        var presistent: Boolean?
    )

    data class BackgroundV3(
        var service_worker: String,
        var type: BackgroundV3ServiceWorkerType?
    )

    data class ContentSecurityPolicy(
        var extension_pages: String?,
        var sandbox: String?
    )

    enum class BackgroundV3ServiceWorkerType {
        module
    }

    sealed class ManifestOptionalPermissionsArrOrStrArr {
        data class ManifestOptionalPermissionsArr(var value: List<ManifestOptionalPermissions>?) :
            ManifestOptionalPermissionsArrOrStrArr()

        data class StrArr(var value: List<String>?) : ManifestOptionalPermissionsArrOrStrArr()
    }

    sealed class ManifestPermissionArrOrStrArr {
        data class ManifestPermissionArr(var value: List<ManifestPermissions>?) :
            ManifestPermissionArrOrStrArr()

        data class StrArr(var value: List<String>?) : ManifestPermissionArrOrStrArr()
    }

    data class WebAccessibleResource(
        var resource: List<String>,
        var matches: List<String>
    )

    data class ManifestV2(
        // Required
        override var manifest_version: Number = 2,
        override var name: String,
        override var version: String,
        // Pick one(or more)
        var browser_action: ManifestAction?,
        var page_action: ManifestAction?,

        // Optional
        var background: Background? = null,
        var optional_permissions: ManifestOptionalPermissionsArrOrStrArr?,
        var permissions: ManifestPermissionArrOrStrArr?,
        var web_accessible_resources: List<String>?

    ) : ManifestBase(
        manifest_version,
        name,
        version,
    )

    data class ManifestV3(
        // Required
        override var manifest_version: Number = 3,
        override var name: String,
        override var version: String,
        // Recommended
        // Optional
        var action: ManifestAction?,
        var background: BackgroundV3?,
        var content_scripts_v3: List<ContentScriptV3>?,
        var content_security_policy: ContentSecurityPolicy,
        var host_permissions: List<String>?,
        var optional_permissions: ManifestOptionalPermissionsArrOrStrArr?,
        var optional_host_permissions: List<String>?,
        var permissions: List<Permissions>?,
        var web_accessible_resources: List<WebAccessibleResource>?
    ) : ManifestBase(
        manifest_version,
        name,
        version,
        content_scripts = content_scripts_v3
    )

    sealed class Manifest {
        data class V2(var value: ManifestV2) : Manifest()
        data class V3(var value: ManifestV3) : Manifest()
    }

    data class ManifestIcons(var value: Map<Number, String>)

}